package com.junray.mqttmanager

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log

class MQTTService : Service() {

    private val TAG = "MQTTService_LJM"

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate")
    }

    override fun onBind(intent: Intent?): IBinder? {
        Log.d(TAG, "onBind")
        val config = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent?.getSerializableExtra("config", MQTTConfig::class.java)
        } else {
            intent?.getSerializableExtra("config") as MQTTConfig
        }
        MQTTManager.getInstance().init(this, config!!)
        return CustomBinder()
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.d(TAG, "onUnbind")
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        Log.d(TAG, "onDestroy")
        MQTTManager.getInstance().destroy()
        super.onDestroy()
    }

    companion object {
//        fun bind(context: Context): Connection {
//            val conn = Connection()
//            val intent = Intent(context, MQTTService::class.java)
//            context.bindService(intent, conn, Context.BIND_AUTO_CREATE)
//            return conn
//        }

        fun bind(context: Context, config: MQTTConfig): Connection {
            val conn = Connection()
            val intent = Intent(context, MQTTService::class.java)
            intent.putExtra("config", config)
            context.bindService(intent, conn, Context.BIND_AUTO_CREATE)
            return conn
        }
    }

    inner class CustomBinder : Binder() {
        fun getService(): MQTTService {
            return this@MQTTService
        }
    }

    class Connection : ServiceConnection {
        private var service: MQTTService? = null

        override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
            service = (iBinder as CustomBinder).getService()
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            service = null
        }

        fun sendMsg(msg: String) {
            MQTTManager.getInstance().sendMsg(msg)
        }

        fun sendMsg(topic: String, msg: String) {
            MQTTManager.getInstance().sendMsg(topic, msg)
        }

        fun setCallback(callback: MQTTCallback) {
            MQTTManager.getInstance().setMQTTCallback(callback)
        }

    }
}